package com.example.testinternet;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.logging.SocketHandler;

public class CSActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cs);
        Button btnLogin = (Button) findViewById(R.id.btn_login);
        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Socket socket=new Socket("10.0.2.2",10001);
                            Thread.sleep(2000);
                            String data="tom#123";
                            OutputStream os=socket.getOutputStream();
                            os.write(data.getBytes());
                            os.flush();

                            InputStream is=socket.getInputStream();
                            byte[]buf=new byte[1024];
                            int len=is.read(buf);
                            final String resData=new String(buf,0,len);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(getApplicationContext(),resData,Toast.LENGTH_LONG).show();
                                }
                            });
                            os.close();
                            is.close();

                        }catch (InterruptedException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        });
    }
}
